require('@/styles/index');
var AutoComplete = require('@/components/AutoComplete');
var mock = require('@/mockData');
var VirtualList = require('@/components/VirtualList');
var lazyload = require('common/lazyload');
var utils = require('common/utils');
var EventEmitter = require('common/EventEmitter');
var reactive = require('common/reactive');

window.onload = function () {
  console.warn('========== loading success ======');
  var listState = {
    pageNumber: 1,
    keywords: [],
    totalPage: 0,
  };

  var imgUrlsCache = {};

  updateList(mock.list, { pageNumber: listState.pageNumber });

  reactive.observer(listState, function () {
    updateList(mock.list, listState);
  });

  function updateList(list, option) {
    var filterData =
      option && option.keywords && option.keywords.length
        ? list.filter(function (item) {
            return option.keywords.some(function (keyword) {
              return item.id === keyword.id;
            });
          })
        : list;

    var pageSize = option.pageSize || 20;

    var curryPaging = utils.curry(utils.pagination)(filterData, pageSize);
    var totalPage = Math.ceil(filterData.length / pageSize);

    document.querySelector('.page-info').innerText = option.pageNumber + '/' + totalPage;

    var pagingData = curryPaging(option.pageNumber);

    console.log('filterData', filterData);
    console.log('pagingData', pagingData);

    new VirtualList(
      '.card-list',
      pagingData,
      function (data) {
        function lazyloadFlag(imgUrl) {
          return imgUrlsCache[imgUrl]
            ? {
                class: ' ',
                url: imgUrl,
              }
            : {
                class: ' lazyload',
                url: 'https://via.placeholder.com/100',
              };
        }

        var avatarInfo = lazyloadFlag(data.avatar);
        var coverInfo = lazyloadFlag(data.img);

        var card = new DOMParser()
          .parseFromString(
            '<div class="card" data-key="' +
              data.id +
              '">' +
              '<div class="card-main">' +
              '<p>' +
              '<img src="' +
              avatarInfo.url +
              '" data-src="' +
              data.avatar +
              '" alt="' +
              data.name +
              '" class="card-avatar' +
              avatarInfo.class +
              '"/>' +
              '<span>' +
              data.name +
              '</span>' +
              '</p>' +
              '<p class="card-desc text-ellipsis">' +
              data.desc +
              '</p>' +
              '</div>' +
              '<div class="card-img">' +
              '<img  src="' +
              coverInfo.url +
              '" data-src="' +
              data.img +
              '" alt="' +
              data.name +
              '" width="100%" class="' +
              coverInfo.class +
              '"/>' +
              '</div>' +
              '</div>',
            'text/html',
          )
          .querySelector('.card');
        return card;
      },
      {
        dynamicHeight: true,
        estimateListHeight: 100,
        throttleTime: 300,
        renderedCallback: function () {
          lazyload({
            el: '.card-list',
            threshold: 100,
            callback: function (imgUrl) {
              imgUrlsCache[imgUrl] = true;
            },
          });
        },
      },
    );
  }

  var autoComplete = new AutoComplete('.form');
  autoComplete.init(mock.list);

  document.querySelector('.next-page').addEventListener('click', function () {
    var totalPage = document.querySelector('.page-info').innerText.split('/').pop();
    if (listState.pageNumber >= totalPage) return;
    listState.pageNumber += 1;
  });
  document.querySelector('.last-page').addEventListener('click', function () {
    if (listState.pageNumber <= 1) return;
    listState.pageNumber -= 1;
  });

  EventEmitter.on('keywords-change', function (keywords) {
    console.log('emit data', keywords);
    listState.keywords = keywords.slice();
    listState.pageNumber = 1;
  });
};
